package com.hengpeng.itfin.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hengpeng.common.file.WriteFile;
import com.hengpeng.common.util.StringHelper;

/**
 * <pre>
 * 写文件
 * </pre>
 * @author chenhui
 * @version 1.0, 2014-2-15
 */
public class WriteFileImpl implements WriteFile
{
	public final Log log = LogFactory.getLog(WriteFileImpl.class);

	/**
	 * 临时文件后缀名
	 */
	private final static String TEMP_FILE_SUFFIX = ".temp";

	private String content;

	public WriteFileImpl(String content)
	{
		if (StringHelper.isEmpty(content))
		{
			this.content = "";
		}
		else
		{
			this.content = content;
		}
	}

	@Override
	public boolean write(File file)
	{
		try
		{
			String filePath = file.getAbsolutePath();
			if (filePath.contains(TEMP_FILE_SUFFIX))
			{
				filePath = filePath.substring(0, filePath.indexOf(TEMP_FILE_SUFFIX));
			}
			File existFile = new File(filePath);
			if (existFile.exists() && existFile.isFile())
			{
				throw new Exception("文件已存在不能重复生成:" + filePath);
			}
			FileOutputStream fos = new FileOutputStream(file);
			Writer out = new OutputStreamWriter(fos, "GBK");
			out.write(content);
			out.close();
			fos.close();
			return true;
		}
		catch (Exception e)
		{
			log.error("写入文件{" + file.getName() + "}异常", e);
			throw new RuntimeException("生成文件发生异常:" + file.getName(), e);
		}
	}
}
